package com.blackhorse.service.impl;

import com.blackhorse.dao.OrderDao;
import com.blackhorse.dao.TxLogDao;
import com.blackhorse.domain.Order;
import com.blackhorse.domain.TxLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * 测试rocketmq事务消息
 *
 * @author laizhe
 */
@Slf4j
@Service
public class OrderServiceImpl4 {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private TxLogDao txLogDao;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 下单前发送半事务消息
     */
    public void createOrderBefore(Order order) {
        //准备事务ID
        String txId = UUID.randomUUID().toString();
        //1.发送半事务消息，携带事务ID
        Message<Order> message = MessageBuilder
                .withPayload(order)
                .setHeader("txId", txId)
                .build();
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction("tx_producer_group",
                "tx_topic",
                message,
                order);
        log.info("createOrderBefore sendMessageInTransaction result:{}", sendResult);
    }

    /**
     * 下单操作本地事务
     */
    @Transactional(rollbackFor = Exception.class)
    public void createOrder(String txId, Order order) {
        //保存订单
        orderDao.save(order);

        //保存事务日志
        TxLog txLog = new TxLog();
        txLog.setTxId(txId);
        txLog.setDate(new Date());
        txLogDao.save(txLog);
    }

    public TxLog queryTxLog(String txId) {
        return txLogDao.findById(txId).orElse(null);
    }
}
